Java syntax
part 28/46 · 86.7 KB total
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
All the statements in Java must reside within methods. Methods are similar to functions except they belong to classes. A method has a return value, a name and usually some parameters initialized when it is called with some arguments. Similar to C++, methods returning nothing have return type declared as void. Unlike in C++, methods in Java are not allowed to have default argument values and methods are usually overloaded instead.
class Foo {
int bar(int a, int b) {
return (a*2) + b;
}
/* Overloaded method with the same name but different set of arguments */
int bar(int a) {
return a*2;
}
}
A method is called using . notation on an object, or in the case of a static method, also on the name of a class.
Foo foo = new Foo();
int result = foo.bar(7, 2); // Non-static method is called on foo
int finalResult = Math.abs(result); // Static method call
The throws keyword indicates that a method throws an exception. All checked exceptions must be listed in a comma-separated list.
void openStream() throws IOException, myException { // Indicates that IOException may be thrown
}
Modifiers
• abstract - Abstract methods can be present only in abstract classes, such methods have no body and must be overridden in a subclass unless it is abstract itself.
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────